package com.study.zouchao.superproject.comtasklist.fragment.presenter;

import android.annotation.TargetApi;
import android.content.Context;
import android.icu.text.UFormat;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.base_zou.cache.ComTaskListCacheUtil;
import com.study.zouchao.superproject.comtaskdetail.TaskDetailActivity;
import com.study.zouchao.superproject.comtasklist.fragment.ITaskListContract;
import com.study.zouchao.superproject.comtasklist.fragment.adapter.TaskListAdapter;
import com.study.zouchao.superproject.comtasklist.fragment.model.TaskListModel;
import com.study.zouchao.superproject.comtasklist.fragment.model.entity.TaskListResult;
import com.study.zouchao.superproject.searchweather.SearchWeatherModel;
import com.study.zouchao.superproject.travellist.TravelContract;
import com.study.zouchao.superproject.travellist.adapter.TravelRecyclerViewAdapter;
import com.study.zouchao.superproject.travellist.entity.TravelListResult;
import com.study.zouchao.superproject.travellist.model.TravelCacheModel;
import com.study.zouchao.superproject.travellist.model.TravelModel;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.LogLongUtil;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/6/20.
 */

public class TaskListPresenter implements ITaskListContract.ITaskListPresenter, TaskListAdapter.IRvItemClickListener {

    private ITaskListContract.ITaskListView mView;

    private List<TaskListResult.TaskItemBean> mData;
    private TaskListAdapter mAdapter;
    private Context mContext;

    private Subscription mSupConn;

    //用户操作：下拉刷新
    private static final String ACTION_REFRESHING = "ACTION_REFRESHING";
    //用户操作：上滑更多
    private static final String ACTION_SEE_MORE = "ACTION_SEE_MORE";

    private int mPageSize = 5;
    private int mPageIndex = 1;
    private int mTotalSize = 0;

    private TaskListModel mConnModel;

    //正在加载数据
    private boolean mIsLoadingData = false;

    public TaskListPresenter(Context context, ITaskListContract.ITaskListView view) {
        mContext = context;
        mConnModel = new TaskListModel();
        mView = view;
        init();
    }
    private void init() {
        mData = new ArrayList<>();
        mAdapter = new TaskListAdapter(mContext, mData);
    }


    private void toggleLoading(String userAction, boolean isShow) {
        if (userAction.equals(ACTION_REFRESHING))   mView.showRefreshingLoading(isShow);
        if(userAction.equals(ACTION_SEE_MORE))      mView.showSeeMoreLoading(isShow);
    }

    @Override
    public void onRefreshingData() {
        conn(ACTION_REFRESHING);
    }

    @Override
    public void loadSeeMore() {
        if (mIsLoadingData)      return;
        //无数据的情况只能下拉刷新不允许上滑更多   1是footView
        if (mAdapter.getItemCount()<=1)   return;
        if ((mPageIndex) >= mTotalSize) {
//            ToastUtils.showShort(App.getAppContext(), "无更多数据");
            mView.showSnackBar("Warn！！无更多数据！！");
            return;
        }
        conn(ACTION_SEE_MORE);
    }

    private Map<String, String> getRequestParams(String action) {
        if(action.equals(ACTION_REFRESHING)) mPageIndex = 1;
        if (action.equals(ACTION_SEE_MORE))  mPageIndex += 1;
        Map<String, String> params = new HashMap<>();

        params.put("currentRows", mPageSize+"");
        params.put("currentPage", mPageIndex+"");
        return params;
    }

    private void conn(final String action) {
        if (!isValidUserAction(action)) {
            Toast.makeText(mContext, "用户操作有误", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> requestParams = getRequestParams(action);
        if (requestParams==null || requestParams.isEmpty()) return;
        toggleLoading(action, true);
        mIsLoadingData = true;
        mSupConn = mConnModel.listTaskList(requestParams)
                .subscribe(new Action1<TaskListResult>() {
                    @Override
                    public void call(TaskListResult taskListResult) {
                        judgeConnResult(taskListResult, action);
                        toggleLoading(action, false);
                        mIsLoadingData = false;
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        failGetList(throwable, action);
                        if (action.equals(ACTION_REFRESHING))
                            loadComTaskFromCache();
                        toggleLoading(action, false);
                        mIsLoadingData = false;
//                        mView.showSnackBar("获取数据失败、请稍后再试...");
                    }
                });
    }

    private void judgeConnResult(TaskListResult taskListResult, final String action) {
        switch (taskListResult.getCode()) {
            case 21101 :
                successGetList(taskListResult, action);
                break;
            default:
                mView.showSnackBar("获取数据失败、请稍后再试...");
                if (action.equals(ACTION_REFRESHING))
                    loadComTaskFromCache();
                break;
        }
    }


    private void successGetList(TaskListResult result, String action) {
        if (action.equals(ACTION_REFRESHING)) {
            mData.clear();
            saveComTask2Cache(result);
            mData.clear();
            mView.showSnackBar("任务列表更新成功", Snackbar.LENGTH_LONG);
        }
//       loadComTaskFromCache();
        loadComTask(result);
    }

    private void loadComTask(TaskListResult result) {
        if (result == null) return;
        mTotalSize = result.getPageNum();
        Log.d("pageSize", result.getPageNum()+"");
        List<TaskListResult.TaskItemBean> newData = result.getData();
        mData.addAll(newData);
        mAdapter.notifyDataSetChanged();
    }

    private void loadComTaskFromCache() {
        TaskListResult result =
                ComTaskListCacheUtil.getComTaskListCacheByList(mContext);
        if (result == null) return;
        mTotalSize = result.getPageNum();
        Log.d("pageSize", result.getPageNum()+"");
        List<TaskListResult.TaskItemBean> newData = result.getData();
        mData.clear();
        mData.addAll(newData);
        mAdapter.notifyDataSetChanged();
    }

    private void saveComTask2Cache(TaskListResult result) {
        ComTaskListCacheUtil.saveComTaskListCache(mContext, result);
    }

    private void failGetList(Throwable throwable, String action) {
        throwable.printStackTrace();
        mView.showSnackBar((StringUtils.isEmpty(throwable.getMessage()) ? "加载失败、请稍后再试" : throwable.getMessage()));
    }


    private boolean isValidUserAction(String action) {
        return (action!=null) && (action.equals(ACTION_REFRESHING) || action.equals(ACTION_SEE_MORE));
    }

    @Override
    public void initRecyclerView(RecyclerView rv) {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mData = new ArrayList<>();
        //为RecyclerView加Adapter
        mAdapter = new TaskListAdapter(mContext, mData);
        View footLoadingView = LayoutInflater.from(mContext).inflate(R.layout.footview_recyclerview, rv, false);
        mAdapter.setFooterView(footLoadingView);
        mAdapter.setOnItemClickListener(this);
        mView.setSeeMoreLoading(footLoadingView);
        rv.setAdapter(mAdapter);
        //添加上滑更多监听器
        //请求数据
        conn(ACTION_REFRESHING);
    }

    @Override
    public void onDestroyPresente() {
        if (mSupConn!=null && !mSupConn.isUnsubscribed())    mSupConn.unsubscribe();
    }

    @Override
    public void onItemClick(View v, int taskId) {
        TaskDetailActivity.actionStartTaskDetailActivity(mContext, taskId);
    }
}
